import Vue from 'vue'
import { createApp } from '../app'
const { app, router, store } = createApp()

if (window.__INITIAL_STATE__) {
  store.replaceState(window.__INITIAL_STATE__)
}

Vue.mixin({
  beforeRouteUpdate (to, from, next) {
    console.log('beforeRouteUpdate');
    const { asyncData } = this.$options.methods

    if (asyncData) {
      asyncData({
        store: this.$store,
        route: to
      }).then(next).catch(next)
    } else {
      next()
    }
  }
})

Vue.mixin({
  beforeMount () {
    console.log('beforeMount')
    const { asyncData } = this.$options.methods

    if (asyncData) {
      console.log('loading start')

      // 将获取数据操作分配给 promise
      // 以便在组件中，我们可以在数据准备就绪后
      // 通过运行 `this.dataPromise.then(...)` 来执行其他任务
      this.dataPromise = asyncData({
        store: this.$store,
        route: this.$route
      })

      // debugger;
      // this.dataPromise
      // .then(()=>{
      //   console.log('successloading end')
      // })
      // .catch(e=>{
      //   console.log('catch loading end')
      // })
    }
  }
})

router.onReady(() => {
  console.log('onReady')
  app.$mount('#app')
  //
  // // 解决之后
  // router.beforeResolve((to, from, next) => {
  //   console.log('beforeResolve');
  //   const matched = router.getMatchedComponents(to)
  //   const prevMatched = router.getMatchedComponents(from)
  //
  //   console.log('matched', matched)
  //   console.log('prevMatched', prevMatched);
  //
  //   let diffed = false
  //   const activated = matched.filter((c, i) => {
  //     return diffed || (diffed = (prevMatched[i] !== c))
  //   })
  //
  //   if (!activated.length) {
  //     return next()
  //   }
  //
  //   console.log('start loading indicator')
  //
  //   Promise.all(activated.map(Component => {
  //
  //     if (Component.options.methods && Component.options.methods.asyncData) {
  //       return Component.options.methods.asyncData({ store, route: to })
  //     }
  //   })).then(() => {
  //
  //     // 停止加载指示器(loading indicator)
  //     console.log('end loading indicator')
  //
  //     next()
  //   }).catch(next)
  // })

  // app.$mount('#app')
})
